<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Accounts extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->layout->loadLayout("account");
        $this->load->model("user_m");
    }

    function login() {
        if ($this->session->userdata('username')) {
            redirect('dashboard');
        }
        $data = array();
        $this->layout->set_title('quang test cai');
        $this->layout->add_meta_tags("keywords", "hehe");
        if ($this->input->server('REQUEST_METHOD') == "POST") {
            $rules = array(
                array(
                    'field' => 'username',
                    'label' => 'Username',
                    'rules' => 'required|valid_email'
                ),
                array(
                    'field' => 'password',
                    'label' => 'Password',
                    'rules' => 'required'
                ),
            );
            $this->form_validation->set_rules($rules);
            if ($this->form_validation->run() == TRUE) {
                $password = $this->input->post('password');
                $username = $this->input->post('username');
                $user = $this->user_m->get_by(array('email' => $username));
                if ($user) {
                    if ($user->password == do_hash($password . $user->salt)) {
                        $this->session->set_userdata('username', $username);
                        $this->session->set_userdata('current_user', $user);
                        redirect('dashboard');
                    } else {
                        $data['form_error_message'] = "Password is incorrect";
                    }
                } else {
                    $data['form_error_message'] = "Username is not exist";
                }
            }
        }
        $this->layout->view('accounts/login_view',$data);
    }

    function logout() {
        $this->session->sess_destroy();
        redirect('accounts/login');
    }

}

?>